package controller

import (
	"errors"
	"notes/config"
	"notes/util"
	"time"

	"github.com/gin-gonic/gin"
)

type loginForm struct {
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
}

// Login 登陆
// @Summary 管理员登陆
// @Description 管理员登陆
// @Tags admin
// @Produce json
// @Consume json
// @Accept json
// @Router /admin/login [post]
// @Param _token query string true "token"
// @Param data body loginForm true "data"
// @Success 200 {object} util.JSONRET "成功返回token"
func Login(c *gin.Context) {
	var loginData loginForm
	var err error
	c.ShouldBind(&loginData)
	data := make(map[string]interface{})

	if loginData.Username != config.Conf.LoginUsername && loginData.Password != config.Conf.LoginPassword {
		err = errors.New("login fail")
	} else {
		var token string
		nowTime := time.Now()
		expireAt := nowTime.Add(time.Duration(config.Conf.Server.TokenExpiredSecond) * time.Second).Unix()
		token, err = util.GenerateToken(loginData.Username, config.Conf.Server.TokenSecret, config.Conf.Name, expireAt)
		if err != nil {
			util.JSON(c, err, nil)
			return
		}

		data = map[string]interface{}{
			"_token":         token,
			"_token_expired": expireAt,
			"lazy_img":       config.Conf.LazyImg,
		}
	}
	util.JSON(c, err, data)
}
